package com.shisfish.library.Controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.shisfish.library.Impl.CoverImpl;
import com.shisfish.library.Model.Cover;
import com.shisfish.library.Prere.Login;
import com.shisfish.library.Utils.Global.GlobalVariable;
import com.shisfish.library.Utils.Global.toJsonUtils;

@Path("cover")
public class CoverController extends GlobalVariable {

	private CoverImpl coverImpl = new CoverImpl();
	
	@POST
	@Path("insertACover/{idadmin}/{isbn}")
	@Consumes({ MediaType.MULTIPART_FORM_DATA, MediaType.APPLICATION_JSON })
	@Produces(MediaType.TEXT_PLAIN)
	public String insertACover(@PathParam("idadmin") String idadmin, @PathParam("isbn") String isbn, 
			@Context HttpServletRequest request) throws Exception {
		
		Map<String, Object> globalMap = new HashMap<String, Object>();
		
		if (Login.isLoginAdmin(idadmin, request)) {
			//得到上传文件的保存目录，将上传的文件存放于WEB-INF目录下，不允许外界直接访问，保证上传文件的安全
			String savePath = request.getSession().getServletContext().getRealPath("/WEB-INF/cover");
			File file = new File(savePath);
			//判断上传文件的保存目录是否存在
			if (!file.exists() && !file.isDirectory()) {
				file.mkdir();
			}
			
			//1、创建一个DiskFileItemFactory工厂
			DiskFileItemFactory diskFileFactory = new DiskFileItemFactory();
			diskFileFactory.setSizeThreshold(1024 * 215);
			
			//2、创建一个文件上传解析器
			ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileFactory);
			//解决上传文件名的中文乱码
			servletFileUpload.setHeaderEncoding("utf-8");
			servletFileUpload.setFileSizeMax(1000 * 1024 * 1024);
			
			//3、判断提交上来的数据是否是上传表单的数据
			if (ServletFileUpload.isMultipartContent(request)) {
				//4、使用ServletFileUpload解析器解析上传数据，解析结果返回的是一个List<FileItem>集合，每一个FileItem对应一个Form表单的输入项
				@SuppressWarnings("unchecked")
				List<FileItem> fileItems = servletFileUpload.parseRequest(request);
				
				for (FileItem fileItem : fileItems) {
					//如果fileitem中封装的是上传文件
					if (!fileItem.isFormField()) {
						
						String filename = fileItem.getName();
						
						if(filename==null || filename.trim().equals("")){
							continue;
						}
						// 文件的后缀
						String prefix = filename.substring(filename.lastIndexOf(".")+1);
						System.out.println(prefix);
						
						String[] picture_suffix = {"bmp", "jpg", "jpge", "png", "gif"};
						
						boolean flag = false;
						for (String string : picture_suffix) {
							if (prefix.toLowerCase().equals(string)) {
								flag = true;
							}
						}
						
						if (flag) {
							//注意：不同的浏览器提交的文件名是不一样的，有些浏览器提交上来的文件名是带有路径的，如：  c:\a\b\1.txt，而有些只是单纯的文件名，如：1.txt
							//处理获取到的上传文件的文件名的路径部分，只保留文件名部分
							filename = filename.substring(filename.lastIndexOf("\\")+1);
							
							//获取item中的上传文件的输入流
							FileInputStream fileinput = (FileInputStream) fileItem.getInputStream();
							
							BufferedInputStream input = new BufferedInputStream(fileinput);
							
							String newFilename = isbn.replaceAll("-", "") + "_cover." + prefix;
							
							FileOutputStream fileoutput = new FileOutputStream(savePath + "/" + newFilename);
							
							BufferedOutputStream output = new BufferedOutputStream(fileoutput);
							
							byte[] bytes = new byte[4096];
							int len = input.read(bytes);
							while (len != -1) {
								output.write(bytes, 0, len);
								len = input.read(bytes);
							}
							output.close();
							fileoutput.close();
							input.close();
							fileinput.close();
							
							fileItem.delete();
							
							Cover cover = new Cover(isbn, idadmin, newFilename);
							
							int flag_1 = coverImpl.insertOne(cover);
							
							if (flag_1 == 1) {
								globalMap.put(STATUS_CODE, SUCCESS);
							} else {
								globalMap.put(STATUS_CODE, INSERT_WR);
							}
							
						}
						
					} else { //如果fileitem中封装的是普通输入项的数据
						String name = fileItem.getFieldName();
						//解决普通输入项的数据的中文乱码问题
						String value = fileItem.getString("UTF-8");
						//value = new String(value.getBytes("iso8859-1"),"UTF-8");
						System.out.println(name + "=" + value);
					}
				}
				
				System.out.println(request.getContextPath());
				System.out.println(request.getSession().getServletContext().getRealPath("/"));
			}
		} else {
			globalMap.put(STATUS_CODE, NOT_LOGGED_IN);
		}
		
		return toJsonUtils.map2Json(globalMap);
	}
	
	@POST
	@Path("updateACover/{idadmin}/{isbn}")
	@Consumes({ MediaType.MULTIPART_FORM_DATA, MediaType.APPLICATION_JSON })
	@Produces(MediaType.TEXT_PLAIN)
	public String updateACover(@PathParam("idadmin") String idadmin, @PathParam("isbn") String isbn, 
			@Context HttpServletRequest request) throws Exception {
		
		Map<String, Object> globalMap = new HashMap<String, Object>();
		
		if (Login.isLoginAdmin(idadmin, request)) {
			//得到上传文件的保存目录，将上传的文件存放于WEB-INF目录下，不允许外界直接访问，保证上传文件的安全
			String savePath = request.getSession().getServletContext().getRealPath("/WEB-INF/cover");
			File file = new File(savePath);
			//判断上传文件的保存目录是否存在
			if (!file.exists() && !file.isDirectory()) {
				file.mkdir();
			}
			
			//1、创建一个DiskFileItemFactory工厂
			DiskFileItemFactory diskFileFactory = new DiskFileItemFactory();
			diskFileFactory.setSizeThreshold(1024 * 215);
			
			//2、创建一个文件上传解析器
			ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileFactory);
			//解决上传文件名的中文乱码
			servletFileUpload.setHeaderEncoding("utf-8");
			servletFileUpload.setFileSizeMax(1000 * 1024 * 1024);
			
			//3、判断提交上来的数据是否是上传表单的数据
			if (ServletFileUpload.isMultipartContent(request)) {
				//4、使用ServletFileUpload解析器解析上传数据，解析结果返回的是一个List<FileItem>集合，每一个FileItem对应一个Form表单的输入项
				@SuppressWarnings("unchecked")
				List<FileItem> fileItems = servletFileUpload.parseRequest(request);
				
				for (FileItem fileItem : fileItems) {
					//如果fileitem中封装的是上传文件
					if (!fileItem.isFormField()) {
						
						String filename = fileItem.getName();
						
						if(filename==null || filename.trim().equals("")){
							continue;
						}
						// 文件的后缀
						String prefix = filename.substring(filename.lastIndexOf(".")+1);
						System.out.println(prefix);
						
						String[] picture_suffix = {"bmp", "jpg", "jpge", "png", "gif"};
						
						boolean flag = false;
						for (String string : picture_suffix) {
							if (prefix.toLowerCase().equals(string)) {
								flag = true;
							}
						}
						
						if (flag) {
							//注意：不同的浏览器提交的文件名是不一样的，有些浏览器提交上来的文件名是带有路径的，如：  c:\a\b\1.txt，而有些只是单纯的文件名，如：1.txt
							//处理获取到的上传文件的文件名的路径部分，只保留文件名部分
							filename = filename.substring(filename.lastIndexOf("\\")+1);
							
							//获取item中的上传文件的输入流
							FileInputStream fileinput = (FileInputStream) fileItem.getInputStream();
							
							BufferedInputStream input = new BufferedInputStream(fileinput);
							
							String newFilename = isbn.replaceAll("-", "") + "_cover." + prefix;
							
							FileOutputStream fileoutput = new FileOutputStream(savePath + "/" + newFilename);
							
							BufferedOutputStream output = new BufferedOutputStream(fileoutput);
							
							byte[] bytes = new byte[4096];
							int len = input.read(bytes);
							while (len != -1) {
								output.write(bytes, 0, len);
								len = input.read(bytes);
							}
							output.close();
							fileoutput.close();
							input.close();
							fileinput.close();
							
							fileItem.delete();
							
							List<Cover> covers = coverImpl.selectByKey(isbn);
							if (covers.size() > 0) {
								Cover cover = covers.get(0);
								cover.setPic(newFilename);
								cover.setAdder(idadmin);
								
								int flag_1 = coverImpl.updateOne(cover);
								
								if (flag_1 == 1) {
									globalMap.put(STATUS_CODE, SUCCESS);
								} else {
									globalMap.put(STATUS_CODE, INSERT_WR);
								}
							} else if (covers.size() == 0) {
								globalMap.put(STATUS_CODE, SELECT_EMPTY);
							} else {
								globalMap.put(STATUS_CODE, SELECT_WR);
							}
							
						}
						
					} else { //如果fileitem中封装的是普通输入项的数据
						String name = fileItem.getFieldName();
						//解决普通输入项的数据的中文乱码问题
						String value = fileItem.getString("UTF-8");
						//value = new String(value.getBytes("iso8859-1"),"UTF-8");
						System.out.println(name + "=" + value);
					}
				}
				
				System.out.println(request.getContextPath());
				System.out.println(request.getSession().getServletContext().getRealPath("/"));
			}
		} else {
			globalMap.put(STATUS_CODE, NOT_LOGGED_IN);
		}
		
		return toJsonUtils.map2Json(globalMap);
	}
	
	@POST
	@Path("insertPic/{idadmin}/{isbn}")
	@Consumes({ MediaType.MULTIPART_FORM_DATA, MediaType.APPLICATION_JSON })
	@Produces(MediaType.TEXT_PLAIN)
	public String insertPic(@PathParam("idadmin") String idadmin, @PathParam("isbn") String isbn, 
			@Context HttpServletRequest request) throws IOException {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		
		if (Login.isLoginAdmin(idadmin, request)) {
			String pic = request.getParameter("cover");
			System.out.println(pic);
			String filePath = request.getSession().getServletContext().getRealPath("/");
			System.out.println(filePath);
		} else {
			globalMap.put(STATUS_CODE, NOT_LOGGED_IN);
		}
		
		return toJsonUtils.map2Json(globalMap);
	}
	
	@POST
	@Path("insertAPic/{idadmin}/{isbn}")
	@Produces("application/json; charset=utf-8")
	public String insertAPic(@PathParam("idadmin") String idadmin, @PathParam("isbn") String isbn, 
			@Context HttpServletRequest request, @FormParam("pic") String pic) {
		
		Map<String, Object> globalMap = new HashMap<String, Object>();
		
		if (Login.isLoginAdmin(idadmin, request)) {
			Cover cover = new Cover(isbn, idadmin, pic);
			int flag = coverImpl.insertOne(cover);
			if (flag == 1) {
				globalMap.put(STATUS_CODE, SUCCESS);
			} else {
				globalMap.put(STATUS_CODE, INSERT_WR);
			}
		} else {
			globalMap.put(STATUS_CODE, NOT_LOGGED_IN);
		}
		
		return toJsonUtils.map2Json(globalMap);
	}
	
	@POST
	@Path("updateAPic/{idadmin}/{isbn}")
	@Produces("application/json; charset=utf-8")
	public String updateAPic(@PathParam("idadmin") String idadmin, @PathParam("isbn") String isbn, 
			@Context HttpServletRequest request, @FormParam("pic") String pic) {
		
		Map<String, Object> globalMap = new HashMap<String, Object>();
		
		if (Login.isLoginAdmin(idadmin, request)) {
			Cover cover = coverImpl.selectByISBN(isbn);
			cover.setPic(pic);
			cover.setAdder(idadmin);
			int flag = coverImpl.updateOne(cover);
			if (flag == 1) {
				globalMap.put(STATUS_CODE, SUCCESS);
			} else {
				globalMap.put(STATUS_CODE, INSERT_WR);
			}
		} else {
			globalMap.put(STATUS_CODE, NOT_LOGGED_IN);
		}
		
		return toJsonUtils.map2Json(globalMap);
	}
	
}
